package dbs.mongo;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import org.mongojack.Id;
import org.mongojack.JacksonDBCollection;
import org.mongojack.ObjectId;
import org.mongojack.WriteResult;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongojackHelper
{

	public static void main(final String[] args)
	{
		System.out.println("======================================");
		System.out.println("开始初始化MongoDb相关...");
		initialize();
		System.out.println("初始化MongoDb完成!");

		JacksonDBCollection<User, String> coll = JacksonDBCollection.wrap(_Collection, User.class, String.class);
		coll.drop();
		System.out.println("清除数据库内容完成!");

		System.out.println();
		System.out.println("====> CRUD:Create...");

		List<String> ids = new ArrayList<>();

		for (int n = 1; n <= 300; n++)
		{
			User user = new User();
			user.setEmail(n + "@gmail.com");
			user.setName("user" + n);
			user.setBirthday(DateTime.now());

			WriteResult<User, String> result = coll.insert(user);
			String id = result.getSavedId();
			ids.add(id);
		}

		System.out.println("向数据插入数据完成,共计" + ids.size() + "条");
		System.out.println("从数据库中取出数据，并抽样打印：");
		for (int i = 0; i < ids.size(); i++)
		{
			User user = coll.findOneById(ids.get(i));
			if ((i % 50) == 0)
			{
				System.out.println(user);
			}
		}

		System.out.println();
		System.out.println("====> CRUD:Update...");

		String id = ids.get(ids.size() - 1);
		User oldUser = coll.findOneById(id);

		System.out.println(oldUser);
		oldUser.setEmail("newUser@gmail.com");
		oldUser.setName("newUser");
		// update(Query query, User object)
		coll.update(DBQuery.is("_id", id), oldUser);
		System.out.println(String.format("更新的记录的ID是：", id));

		// findOneById(String id)
		User updateUser = coll.findOneById(id);
		System.out.println(updateUser);

		// find(DBObject query)
		DBCursor<User> cursor = coll.find(new BasicDBObject().append("name", "newUser").append("email", "newUser@gmail.com"));
		System.out.println(cursor.next());

		// remove(Query query)
		coll.remove(DBQuery.or(DBQuery.is("name", "newUser")));
		// find(Query query)
		cursor = coll.find(DBQuery.or(DBQuery.is("name", "newUser")));
		while (cursor.hasNext())
		{
			User user = cursor.next();
			System.out.println(user);
		}
	}

	// / init begin ///
	protected static DBCollection _Collection;

	protected static void initialize()
	{
		ServerAddress address = createServerAddress();
		_Collection = createCollection(address);
	}

	protected static ServerAddress createServerAddress()
	{
		ServerAddress address = null;
		try
		{
			address = new ServerAddress("127.0.0.1", 27017);
		}
		catch (UnknownHostException e)
		{
		}
		return address;
	}

	protected static DBCollection createCollection(final ServerAddress address)
	{
		MongoClient mongoClient = new MongoClient(address);
		DB db = mongoClient.getDB("test");
		String collectionName = String.format("%s.%s", "test_collection", "subcollection");
		DBCollection collection = db.getCollection(collectionName);
		return collection;
	}
	// / init end ///
}

class User
{
	private String id;
	private String name;
	private String email;
	private DateTime birthday;

	@Id
	@ObjectId
	public String getId()
	{
		return id;
	}

	@Id
	@ObjectId
	public void setId(final String id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(final String name)
	{
		this.name = name;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(final String email)
	{
		this.email = email;
	}

	@JsonSerialize(using = DateTimeSerializer.class)
	public DateTime getBirthday()
	{
		return birthday;
	}

	public void setBirthday(final DateTime birthday)
	{
		this.birthday = birthday;
	}


	@Override
	public String toString()
	{
		return "User [id=" + id + ", name=" + name + ", email=" + email + ", birthday=" + birthday + "]";
	}

}
